package com.lxl.bt.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lxl.bt.R;
import com.lxl.bt.activity.BaseFragment;
import com.lxl.bt.activity.WebviewActivity;
import com.lxl.bt.bean.MessageBean;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.lxl.bt.util.EnvironmentUtil;
import com.lxl.bt.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Create by lvxinlong
 * on btc
 * on 2021年3月6日10:00:20
 **/
public class MessageListFragment extends BaseFragment {


    @BindView(R.id.rcv)
    RecyclerView rcv;
    @BindView(R.id.llNodata)
    LinearLayout llNodata;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private Unbinder unbinder;
    ACache aCache;
    BaseQuickAdapter<MessageBean, BaseViewHolder> sysAdapter;
    int pageNo = 0;

    public static MessageListFragment newInstance(String type) {
        Bundle bundle = new Bundle();
        MessageListFragment fragment = new MessageListFragment();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_btclist, container, false);
//        ((BaseActivity) getActivity()).setStatusBarFullTransparent();

        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, view);
//        EventBus.getDefault().register(this);
        aCache = ACache.get(getActivity());
        sysAdapter = new BaseQuickAdapter<MessageBean, BaseViewHolder>(R.layout.item_message) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, MessageBean bean) {
            }


            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder baseViewHolder, int position) {
              baseViewHolder.setText(R.id.tvName,getItem(position).getTitleName());
              baseViewHolder.setText(R.id.tvTime,getItem(position).getCreateTime()+ getItem(position).getDetailContent());

            }
        };
        rcv.setAdapter(sysAdapter);
        sysAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MessageBean messageBean = (MessageBean) adapter.getData().get(position);
                WebviewActivity.intent(getContext(),messageBean.getTitleName(),messageBean.getDetailContentUrl());
            }
        });
        iniSmartRefreshLayout();
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    private void iniSmartRefreshLayout() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if (!EnvironmentUtil.isNetConnect(getActivity())) {
                    ToastUtil.showToast(getActivity(), "暂无网络");
                    refreshLayout.finishRefresh();
                    return;
                }
                updateData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                pageNo++;
                getData();
            }
        });

    }

    private void updateData() {
        pageNo = 0;
        getData();
    }

    @Override
    public void getData() {
        notifyList();
    }

    public void notifyList() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .getUserInfoByUserId(pageNo,20,null).enqueue(new NetCallback<Result<ArrayList<MessageBean>>>() {
            @Override
            public void onSuccess(Result<ArrayList<MessageBean>> result) {
                if (result.isSuccess()) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (pageNo == 1)
                        sysAdapter.setNewData(result.getData());
                    else
                        sysAdapter.addData(result.getData());

//                    sysAdapter.setEnableLoadMore(result.getTotal() > pageNo ? true : false);
                    pageNo++;
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


//    @Subscribe
//    public void onEventMainThread(EventTagBean event) {
//    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    }

}
